<template>
	<div>
		<!-- 面包屑 -->
		<el-breadcrumb separator-class="el-icon-arrow-right">
			<el-breadcrumb-item :to="{ path: '/layout' }">首页</el-breadcrumb-item>
			<el-breadcrumb-item>用户管理</el-breadcrumb-item>
			<el-breadcrumb-item>用户列表</el-breadcrumb-item>
		</el-breadcrumb>
		<!-- 卡片布局 -->
		<el-card>
			<!-- 植入搜索栏 -->
			<el-row :gutter="20">
				<el-col :span="5"><el-input clearable placeholder="搜索账号" v-model="searchAccount" clearableclear="getUserList"></el-input></el-col>
				<el-col :span="5"><el-input clearable placeholder="搜索名称" v-model="searchName" clearableclear="getUserList"></el-input></el-col>

				<el-col :span="2">
					<el-button type="primary" @click="getUserList()">
						<el-icon><Search /></el-icon>
					</el-button>
				</el-col>
				<el-col :span="5"><el-button type="primary" @click="showAddBox = true">添加用户</el-button></el-col>
			</el-row>
			<!-- 放入table -->
			<el-table
				:data="userList"
				style="width: 100%; height: 550px; margin-top:10px;"
				border
				:header-cell-style="{ height: '37px', padding: '0' }"
				:row-style="{ height: '37px' }"
				:cell-style="{ padding: '0' }"
			>
				<!-- 数据绑定 -->
				<el-table-column fixed label="用户id" width="80" prop="id"></el-table-column>
				<el-table-column fixed label="用户名称" width="100" prop="username"></el-table-column>
				<el-table-column label="用户帐号" width="180" prop="account"></el-table-column>
				<el-table-column label="用户权限" width="180" prop="role">
					<template #default="scope">
						<el-select @change="setRole(scope.row)" class="el-col-sm-22" size="small" v-model="scope.row.role">
							<el-option v-for="item in roleOptions" :key="item.value" :label="item.label" :value="item.value" />
						</el-select>
					</template>
				</el-table-column>

				<el-table-column label="手机号码" width="180" prop="phone"></el-table-column>
				<el-table-column label="用户邮箱" width="180" prop="email"></el-table-column>
				<el-table-column label="用户性别" width="120" prop="sex"></el-table-column>
				<el-table-column label="可用性" width="100" prop="enable">
					<template #default="scope">
						<el-select @change="changeEnableOrLock(scope.row, true)" class="el-col-sm-22" size="small" v-model="scope.row.enable">
							<el-option v-for="item in enableOptions" :key="item.value" :label="item.label" :value="item.value" />
						</el-select>
					</template>
				</el-table-column>
				<el-table-column label="是否锁定" width="100" prop="lockable">
					<template #default="scope">
						<el-select @change="changeEnableOrLock(scope.row, false)" class="el-col-sm-22" size="small" v-model="scope.row.lockable">
							<el-option v-for="item in lockableOptions" :key="item.value" :label="item.label" :value="item.value" />
						</el-select>
					</template>
				</el-table-column>

				<el-table-column label="创建者" width="80" prop="createBy"></el-table-column>
				<el-table-column label="创建时间" width="200" prop="createDate"></el-table-column>
				<el-table-column label="最近修改人" width="100" prop="updateBy"></el-table-column>

				<el-table-column label="最近修改" width="200" prop="lastUpdate"></el-table-column>

				<el-table-column fixed="right" label="操作" width="250">
					<template #default="scope">
						<el-button size="small" @click="showEdit(scope.row)">编辑</el-button>
						<el-button size="small" type="primary" @click="changePassword(scope.row)">修改密码</el-button>
						<el-button size="small" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
					</template>
				</el-table-column>
			</el-table>

			<!-- 分页模块 -->
			<el-pagination
				v-model:current-page="pageNo"
				v-model:page-size="pageSize"
				:page-sizes="[10, 20, 50, 100]"
				:small="false"
				:disabled="false"
				:background="true"
				layout="total, sizes, prev, pager, next"
				:total="totalCount"
				@size-change="onSizeChange"
				@current-change="onPageChange"
			/>

			<!-- 添加会话框 -->
			<el-dialog title="添加用户对话框" v-model="showAddBox" width="30%" :before-close="clearEdit" style="padding: 8px 15px;" @close="onClose">
				<el-form :model="userForm" :rules="userFormRules" ref="userFormRules" label-width="120px">
					<el-form-item label="用户帐号" prop="account"><el-input v-model="userForm.account"></el-input></el-form-item>

					<el-form-item label="用户名" prop="username"><el-input v-model="userForm.username"></el-input></el-form-item>

					<el-form-item label="用户密码" prop="password"><el-input v-model="userForm.password"></el-input></el-form-item>
					<el-form-item label="邮箱" prop="email"><el-input v-model="userForm.email"></el-input></el-form-item>
					<el-form-item label="手机号码" prop="phone"><el-input v-model="userForm.phone"></el-input></el-form-item>

					<el-form-item label="性别" prop="sex">
						<!-- <el-button v-model="userForm.sex"></el-button> -->
						<template #default="scope">
							<el-radio v-model="userForm.sex" label="男">男</el-radio>
							<el-radio v-model="userForm.sex" label="女">女</el-radio>
						</template>
					</el-form-item>
					<el-form-item class="dialog-footer">
						<el-button @click="clearEdit">取消</el-button>
						<el-button type="primary" @click="saveUserData('userFormRules')">确定</el-button>
					</el-form-item>
				</el-form>
			</el-dialog>
			<!-- 编辑会话框 -->
			<el-dialog title="编辑用户" v-model="showEditBox" width="40%" :before-close="clearEdit" style="padding: 8px 15px;" @close="onClose">
				<el-form :model="userForm" :rules="userFormRules" ref="userFormRules" label-width="120px">
					<!-- --- [添加其它同类项]开始 --- -->
					<!-- 记得修改prop和下面的v-model[userForm.xxx] -->
					<el-form-item label="用户帐号" prop="account" style="margin-top:5px;"><el-input v-model="userForm.account" placeholder="暂无内容"></el-input></el-form-item>
					<el-form-item label="用户名称" prop="username" style="margin-top:5px;"><el-input v-model="userForm.username" placeholder="暂无内容"></el-input></el-form-item>
					<!-- <el-form-item label="用户密码" prop="password" style="margin-top:5px;"><el-input v-model="userForm.password" placeholder="暂无内容"></el-input></el-form-item> -->
					<el-form-item label="用户手机" prop="phone" style="margin-top:5px;"><el-input v-model="userForm.phone" placeholder="暂无内容"></el-input></el-form-item>
					<el-form-item label="用户邮箱" prop="email" style="margin-top:5px;"><el-input v-model="userForm.email" placeholder="暂无内容"></el-input></el-form-item>
					<el-form-item label="性别" prop="sex" style="margin-top:5px;margin-bottom:5px;">
						<el-radio-group v-model="userForm.sex">
							<el-radio label="男"></el-radio>
							<el-radio label="女"></el-radio>
						</el-radio-group>
					</el-form-item>
				</el-form>
				<span slot="footer" class="dialog-footer">
					<el-button @click="clearEdit">取消</el-button>
					<el-button type="primary" @click="handleEdit(userForm.id, 'userFormRules')">确定</el-button>
				</span>
			</el-dialog>
		</el-card>
	</div>
</template>
<script>
import { editUser, addUser, deleteUser, getUserList } from '@/api/user.js';
import { getRoleList } from '@/api/role.js';
import { Search } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';
export default {
	name: 'userList',
	data() {
		return {
			enableOptions: [
				{
					value: '0',
					label: '是'
				},
				{
					value: '1',
					label: '否'
				}
			],
			lockableOptions: [
				{
					value: '1',
					label: '是'
				},
				{
					value: '0',
					label: '否'
				}
			],
			roleOptions: [],

			showEditBox: false,
			showAddBox: false,
			searchStr: '',
			pageNo: 1,
			pageSize: 10,
			totalCount: 0,
			searchAccount: '',
			searchName: '',

			userForm: {
				id: '',
				account: '',
				username: '',
				password: '',
				email: '',
				sex: '',
				createDate: '',
				isEdit: ''
			},

			trigger: 'blur',
			userFormRules: {
				account: [
					{
						required: true,
						pattern: /^[A-Za-z0-9]+$/,
						message: '用户账号仅允许输入[数字，及字母大小写]',
						trigger: 'blur'
					},
					{ required: true, message: '请输入用户帐号', trigger: 'blur' }
				],
				username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
				password: [
					{
						required: true,
						message: '请输入用户密码',
						trigger: 'blur'
					},
					{ min: 8, message: '长度必须大于8位', trigger: 'blur' }
				],
				email: [
					{ required: true, message: '请输入用户邮箱', trigger: 'blur' },
					{
						required: true,
						pattern: /[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?/,
						message: '不符合邮箱格式',
						trigger: 'blur'
					}
				],
				sex: [{ required: true, message: '请选择用户性别', trigger: 'blur' }],
				phone: [
					{ required: true, message: '请输入用户手机', trigger: 'blur' },
					{
						required: true,
						pattern: /^1[3|4|5|8][0-9]\d{4,8}/,
						message: '不符合手机格式',
						trigger: 'blur'
					}
				]
			},

			userList: []
		};
	},
	methods: {
		getUserList() {
			this.searchStr = {
				account: this.searchAccount,
				name: this.searchName
			};
			const param = { page: this.pageNo, limit: this.pageSize, searchStr: this.searchStr };
			getUserList(param).then(resp => {
				this.totalCount = resp.total;
				this.userList = resp.rows;
				this.userList.forEach(user => {
					const roleId = user.role;
					this.roleOptions.forEach(role => {
						if (user.role == role.value) {
							user.role = role.label;
						}
					});
					if (roleId == user.role) {
						user.role = this.roleOptions[1].label;
					}
				});
			});
		},
		initRoleOptions() {
			const param = { page: '', limit: '' };

			getRoleList(param).then(resp => {
				resp.rows.forEach(role => {
					this.roleOptions.push({ value: role.id, label: role.roleDesc });
				});
				this.getUserList();
			});
		},
		setRole(row) {
			//拿修改数据，update
			const param = { id: row.id, role: row.role, account: row.account };
			editUser(param)
				.then(resp => {
          if (resp.success){
					this.$message({
						type: 'success',
						message: '已修改'
					});
          }
				})
				.catch(ex => {
					this.$message({
						type: 'error',
						message: '修改失败' + ex
					});
				});
		},
		changeEnableOrLock(row, judge) {
			console.log(row);
			var param = [];
			console.log(judge);
			if (judge) {
				param = { id: row.id, enable: row.enable };
			} else {
				param = { id: row.id, lockable: row.lockable };
			}
			console.log(param);
			editUser(param)
				.then(resp => {
          if (resp.success){

					this.$message({
						type: 'success',
						message: '已修改'
					});
          }
				})
				.catch(ex => {
					this.$message({
						type: 'error',
						message: '修改失败' + ex
					});
				});
		},
		changePassword(row) {
			ElMessageBox.prompt('在此输入用户' + row.username + '的新密码', '修改用户密码', {
				confirmButtonText: '确认',
				cancelButtonText: '取消',

				inputValidator(value) {
					if (value.length < 8) {
						return '密码长度不能小于8位';
					}
				},
				inputErrorMessage: '密码长度不能小于8位'
			})
				.then(({ value }) => {
					const param = { id: row.id, password: value };
					editUser(param).then(resp => {
						if (resp.success) {
							ElMessage({
								type: 'success',
								message: row.username + '的新密码为：' + value + '	请牢记！！'
							});
						} else {
							ElMessage({
								type: 'error',
								message: '修改失败'
							});
						}
					});
				})
				.catch(() => {
					ElMessage({
						type: 'info',
						message: '取消操作'
					});
				});
		},
		onSizeChange(pageSize) {
			this.pageNo = 1;
			this.pageSize = pageSize;
			this.getUserList();
		},
		onPageChange(page) {
			this.pageNo = page;
			this.getUserList();
		},
		onClose() {
			this.userForm = [];
		},
		saveUserData(formName) {
			this.$refs[formName].validate(valid => {
				if (valid) {
					console.log('验证通过');
					this.$confirm('此操作将添加该用户, 是否继续?', '提示', {
						confirmButtonText: '确定',
						cancelButtonText: '取消',
						type: 'warning'
					})
						.then(() => {
							const param = {
								id: '',
								account: this.userForm.account,
								username: this.userForm.username,
								password: this.userForm.password,
								sex: this.userForm.sex,
								phone: this.userForm.phone,
								email: this.userForm.email
							};

							addUser(param).then(resp => {
								this.showAddBox = false;
								this.userForm = [];
								this.getUserList();
							});
						})
						.catch(() => {
							// console.log(message)
							this.$message({
								type: 'error',
								message: '已取消添加'
							});
						});
				} else {
					console.log('验证失败');
					return false;
				}
			});
		},

		handleDelete(index, row) {
			this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			})
				.then(() => {
					const delId = { id: row.id };

					deleteUser(delId).then(resp => {
            if (resp.success){
						this.$message({
							type: 'success',
							message: '删除成功!'
						});
            }
						this.getUserList();
					});
				})
				.catch(() => {
					this.$message({
						type: 'error',
						message: '删除失败！'
					});
				});
		},

		showEdit(row) {
			//设置id
			this.userForm.id = row.id;
			console.log('row.id-----' + row.id);
			//设置表单默认值
			this.userForm.account = row.account;
			this.userForm.username = row.username;
			this.userForm.password = row.password;
			this.userForm.email = row.email;
			this.userForm.phone = row.phone;
			this.userForm.sex = row.sex;
			console.log('这里是showEdit-----------------');

			console.log(this.userForm);
			//弹框
			this.showEditBox = true;
		},
		//  ---清空编辑框所修改的函数
		clearEdit() {
			//清空表单默认值
			this.userForm = [];

			//关闭弹框
			this.showAddBox = false;
			this.showEditBox = false;
		},
		//  ---确认函数
		handleEdit(editId, formName) {
			this.$refs[formName].validate(valid => {
				if (valid) {
					this.$confirm('此操作将修改该用户, 是否继续?', '提示', {
						confirmButtonText: '确定',
						cancelButtonText: '取消',
						type: 'warning'
					})

						.then(() => {
							console.log(editId);
							const param = {
								id: editId,
								account: this.userForm.account,
								username: this.userForm.username,
								password: this.userForm.password,
								sex: this.userForm.sex,
								phone: this.userForm.phone,
								email: this.userForm.email,
								isEdit: true
							};

							console.log(param);
							editUser(param).then(resp => {
                if (resp.success){
								this.$message({
									type: 'success',
									message: '修改成功!'
								});
                }
								this.clearEdit();
								this.getUserList();
							});
						})
						.catch(() => {
							this.$message({
								type: 'error',
								message: '修改失败！'
							});
						});
				} else {
					console.log('验证失败');
					return false;
				}
			});
		}
	},
	mounted() {
		//组件被挂载自动调用方法

		this.initRoleOptions();
	}
	// 单向数据绑定：userList
};
</script>

<style scoped>
div.el-breadcrumb {
	height: 45px;
}

.el-dialog__body {
	padding: 0px 15px;
}

.el-form-item {
	/* height: 68px; */
}
</style>
